﻿using MQTTnet.Client;
using MQTTnet;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using MQTTnet.Extensions.ManagedClient;

namespace JESAI.MQTT.Client.Clients
{
    public class MQTTManagedClient
    {
        public static async Task Connect_Client()
        {
            /*
            *此示例创建一个简单的托管MQTT客户端，并连接到一个公共代理。
            *
            *托管客户端扩展现有的_MqttClient_。它增加了以下功能。
            *-当连接丢失时重新连接。
            *-将挂起的消息存储在内部队列中，以便在客户端保持未连接的情况下可以进行排队。
             */

            var mqttFactory = new MqttFactory();

            using (var managedMqttClient = mqttFactory.CreateManagedMqttClient())
            {
                var mqttClientOptions = new MqttClientOptionsBuilder()
                    .WithTcpServer("broker.hivemq.com")
                    .Build();

                var managedMqttClientOptions = new ManagedMqttClientOptionsBuilder()
                    .WithClientOptions(mqttClientOptions)
                    .Build();

                await managedMqttClient.StartAsync(managedMqttClientOptions);

                //不发送应用程序消息。它存储在内部队列中，并且
                //将在连接客户端时发送。
                await managedMqttClient.EnqueueAsync("Topic", "Payload");

                Console.WriteLine("The managed MQTT client is connected.");

                // 等待队列完全处理完毕。
                SpinWait.SpinUntil(() => managedMqttClient.PendingApplicationMessagesCount == 0, 10000);

                Console.WriteLine($"Pending messages = {managedMqttClient.PendingApplicationMessagesCount}");
            }
        }
    }
}
